import { Descriptions, Tag, Modal, Input } from "antd";
import React, { useState } from "react";
import { Image } from "antd";
import zhanwei from "@/assets/images/zhanwei.png";
import { User } from "@/api/interface";
import { updatePassword } from "@/api/modules/user";
import useMessage from "@/hooks/useMessage";
import UpdatePassword from "../UpdatePassword";

interface Props {
	user: User.UserInfo;
}

const UserDetail: React.FC<Props> = ({ user }) => {
	const { contextHolder, success } = useMessage();

	const [isModalOpen, setIsModalOpen] = useState(false);

	const openUpdatePassword = () => {
		setIsModalOpen(true);
	};

	let password = "";
	const passwordChange = (value: string) => {
		password = value;
	};

	const handleOk = async () => {
		const res = await updatePassword(user.id, user.user_name, password);
		if (res.code === 200) {
			handleCancel();
			success("修改密码成功");
		}
	};

	const handleCancel = () => {
		setIsModalOpen(false);
	};

	return (
		<>
			{contextHolder}
			<Descriptions title="用户" bordered column={1}>
				<Descriptions.Item label="id">{user.id}</Descriptions.Item>
				<Descriptions.Item label="账号">{user.user_name}</Descriptions.Item>
				<Descriptions.Item label="用户名">{user.name}</Descriptions.Item>
				<Descriptions.Item label="角色">
					<>
						{user?.roles && user?.roles?.length !== 0
							? (user?.roles as User.Role[]).map(item => (
									<Tag color="cyan" key={item.id}>
										{item.name}
									</Tag>
							  ))
							: "无"}
					</>
				</Descriptions.Item>
				<Descriptions.Item label="头像">
					<Image
						width={100}
						height={100}
						src={user.user_image}
						key={user.id}
						placeholder={<Image width={100} height={100} preview={false} src={zhanwei} />}
					></Image>
				</Descriptions.Item>
				<Descriptions.Item label="创建时间">{user.createdAt}</Descriptions.Item>
				<Descriptions.Item label="更新时间">{user.updatedAt}</Descriptions.Item>
				<Descriptions.Item label="修改密码">{<a onClick={() => openUpdatePassword()}>修改密码</a>}</Descriptions.Item>
			</Descriptions>
			<Modal title="修改密码" visible={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
				<UpdatePassword username={user.user_name} onChange={passwordChange} />
			</Modal>
		</>
	);
};

export default UserDetail;
